package com.iwhalecloud.bss.kite.cucc.service.util;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.AttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.AttrValuesDTO;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.ztesoft.bss.common.util.ContextUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class GoodsUtil {
    /**
     * 资源核查过滤、省份过滤
     */
    public static void checkAndFilterGoods(List<AttrDTO> attrDTOS, String serviceOfferId, String goodsSku) {
        String provinceNbr =  ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        List<DcPublic> dcPublicList = DcPublicCache.getByPkey("2021090112", goodsSku);
        if(KiteListUtils.isNotEmpty(dcPublicList)){
            List<DcPublic> checkList = dcPublicList.stream().filter(dcPublic -> "C".equals(dcPublic.getDflag())).collect(Collectors.toList());
            List<DcPublic> filterList = dcPublicList.stream().filter(dcPublic -> "F".equals(dcPublic.getDflag())).collect(Collectors.toList());
            if(checkList != null && checkList.size() > 0) {
                for (DcPublic dcPublic : checkList) {
                    if(KiteStringUtils.isEmpty(dcPublic.getCodee())){
                        if(dcPublic.getPcode().equals(serviceOfferId)){
                            ErrorConsts.BUSI_COMMON_ERROR.throwOut(dcPublic.getCodea());
                        }
                    }else{
                        if(dcPublic.getPcode().equals(serviceOfferId)&&dcPublic.getCodee().equals(provinceNbr)){
                            ErrorConsts.BUSI_COMMON_ERROR.throwOut(dcPublic.getCodea());
                        }
                    }
                }
            }
            for(AttrDTO attrDTO :attrDTOS){
                if(filterList != null && filterList.size() > 0) {
                    for (DcPublic dcPublic : filterList) {
                        if(dcPublic.getPcode().equals(serviceOfferId)&&attrDTO.getAttrCode().equals(dcPublic.getCodeb())&&dcPublic.getCodee().equals(provinceNbr)){
                            String newGoodsSku = Arrays.stream(attrDTO.getGoodsSku().split(",")).filter(s -> !s.equals(dcPublic.getCodea())).collect(Collectors.joining(","));
                            attrDTO.setGoodsSku(newGoodsSku);
                            List<AttrValuesDTO> attrValuesDTOS = attrDTO.getAttrValues().stream().filter(attrValuesDTO ->!attrValuesDTO.getGoodsSku().equals(dcPublic.getCodea())).collect(Collectors.toList());
                            attrDTO.setAttrValues(attrValuesDTOS);
                        }
                    }
                }
            }
        }

    }
}
